function datac_export()
%
% function to export data files to be read by other programs. Data files
% are read, and exported into a subdirectory with the same name as the main
% filename.
% The file is exported into both text and binary components as
% follows:
% Header (written as text) with filename header.txt
% Index (written
% as text) with filename index.txt
% Notes (written as text, in order of note, into a single file) with
% filename note.txt sf#_protocol,
% df#_protocol, data#_protocol where # is the "block" number. sf (stimulus info)
% and df (acquisition info) are
% currently written as text files. The data is written as a binary file to
% be read by Igor Pro. The file consists of a 256-byte header, followed by
% the data.
% The header includes:
% I16: Version
% I16: Subversion
% I32: Block number from file
% I32: Number of channels
% I32: Number of points in each channel
% F32: Sample rate, microseconds
% (the rest is currently empty)
%
% The data is stored linearly in sequence by channel number i.e, the first
% channel sampled x number of points, second channel x number of points,
% etc. includes the time (first column), followed by the data in  V and I
% traces (subsequent columns).
% Thus, you read the data with a series of "GBWaveLoad" calls
% as follows
% GBWaveLoad /N=Version /S=0 /T={16,16} /W=2 filename
% GBWaveLoad /N=Block /S=32 /T={32,32} /W=1 filename
% GBWaveLoad /N=nchan /S=64 /T={32,32} /W=1 filename
% GBWaveLoad /N=npoints /S=64 /T={32,32} /W=1 filename
% GBWaveLoad /N=srate /S=96 /T={4,4} /W=1 filename
%
% for i = 1 to nchan
%   GBWaveLoad /N=B(block#)_C(chan#)_R(record#) /S=256+32*npoints*(i-1) /T={4,4} /W=1 filename
% end

% requests input filename creates in the same directory as the file a
% subdirectoy with the base filename 4/17/07 Paul Manis.
%

global VOLTAGE CURRENT CONTROL DFILE ALLCH

% first get the filename
[drive, path, ext] = getdriveext;
lookpath= path; % strcat(path, ext);
lookpath
[filename, path] = uigetfile(lookpath, 'Open Data Files', '*.mat');
if(~ischar(filename))
    QueMessage(sprintf('Unable to access file? %s - %s', path, filename));
    result = 1;
    return;
end
setdriveext('path', path);
LASTPATH = path;
lookpath = path;
truefile = strcat(path, filename);
truefile = slash4OS(truefile);
[p f e] = fileparts(truefile);

if(~exist([p f], 'dir'))
    fprintf(1, 'Making Directory %s in directory %s\n', f, p);
    [okflag, message, messid] = mkdir([p '/', f]);
    if(okflag == 1)
        fprintf(1, 'Directory made\n');
    else
        fprintf(1, 'Failed to make directory\n error = %s\n', message);
    end;
end;

v=[];
if(exist(truefile) == 2)
    v = load(truefile, 'Index');
else
    fprintf('File %s not found?\n', filename);
    return;
end;

divider = sprintf('---------------------------------------------------------------------------');

element = fieldnames(v);
INDEX = eval(['v.' char(element)]);
list = {};
list = cellcat(list, sprintf('File: %s', filename));
load(truefile, 'HFILE'); % get the header information.
list = cellcat(list, sprintf('Signature: %s', char(HFILE.Signature.v)));
list = cellcat(list, sprintf('Species: %s  Age: %s Wt: %s  Sex: %s', char(HFILE.Species.v), ...
    char(HFILE.Age.v), char(HFILE.Weight.v), char(HFILE.Sex.v)));
c=char(HFILE.Experiment.v);
list = cellcat(list, 'Experiment:');
for j = 1:size(c,1)
    if(length(c(j,:)) > 0 & ~all(isspace(c(j,:))))
        o = linebreak(c(j,:));
        lend = find(o == 13);
        if(isempty(lend))
            list = cellcat(list, sprintf('   %s', o));
        else
            k = 1;
            for i = 1:length(lend)
                list = cellcat(list, sprintf('    %s', o(k:lend(i)-1)));
                k = lend(i)+1;
            end;
        end;

        %      list = cellcat(list, sprintf('%s', c(j,:)));
    end;
end;
list = cellcat(list, divider);

list = cellcat(list, sprintf('Index for File: %s  ', filename));
s = length(INDEX);
list = cellcat(list, sprintf('    Date      Time     Block   Rec         Type         Info          Name'));
list = cellcat(list, sprintf('---------------------------------------------------------------------------'));
for i = 1:s
            list = cellcat(list, sprintf('%8s  %8s  %4d  %4d  %12s  %12s  %12s', INDEX(i).date, INDEX(i).time, INDEX(i).block, INDEX(i).record, INDEX(i).type, INDEX(i).type2, INDEX(i).MatName));

end;
list = cellcat(list, sprintf('---------------------------------------------------------------------------'));

fprintf(1, 'Would write Index here\n');

data_blks = strmatch('DATA', char(INDEX.type), 'exact');
notes = strmatch('NOTE', char(INDEX.type), 'exact');
note_blks = [INDEX(notes).block]; % identify these by the BLOCK number itself...
data_blks = union(data_blks, notes); % identify indices to all blocks we need to access
% now for each element of the input index, print some information
done_blk = [];
for indxi = 1:length(data_blks) % look for the data in all the blocks (it doesn't hurt to search)
    ind = data_blks(indxi);
    %   fprintf(1, '%d: %d -- %d\n', indxi, INDEX(ind-1).record, INDEX(ind).record);
    this_block = INDEX(ind).block;
    dblk = [];
    if(~isempty(done_blk)) % just prevent warning message
        dblk = find(this_block == done_blk); % check to see if we have already processed block number (union may return multiple indices for same block)
    end;
    [sf df block]= block_info(truefile, this_block);
    fprintf(1, '\n******* BLOCK: %d *******\n', this_block);
    fprintf(1, 'Would write stim and df here\n');
    %print_block(sf);
    %print_block(df);
    
    sblk = sprintf('db_%d', this_block);

    warning off
    a=load(truefile, sblk);
    warning on
    if(~isempty(fieldnames(a)))
        a = eval(['a.' sblk]);
        fprintf(1, 'Block %d has %d records\n', this_block, length(a));
        for j = 1:length(a)
            dbrn = fieldnames(a{j});
            d = eval([sprintf('a{%d}.%s', j, char(dbrn))]);
            [points, chan] = size(d.data);
            %   fprintf(1, 'Record %d is %d channels by %d points\n', j, chan, points);
        end;
        fprintf(1, 'Would write data block here\n');
    end;

    
end;


function [o] = cellcat(in, string)
o = in;
p = length(in) + 1;
o{p} = string;
return;
